package cn.xerllent.wxtp.handler;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import cn.xerllent.wxtp.entity.WxAdmin;
import cn.xerllent.wxtp.entity.WxCorp;
import cn.xerllent.wxtp.service.WxAdminService;
import cn.xerllent.wxtp.service.WxCorpService;
import cn.xerllent.wxtp.service.WxDepartmentService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.bean.WxCpTpAdmin;
import me.chanjar.weixin.cp.bean.WxCpTpAuthInfo;
import me.chanjar.weixin.cp.bean.WxCpTpPermanentCodeInfo;
import me.chanjar.weixin.cp.bean.message.WxCpTpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;

/**
 * @author sxh
 * 企业变更授权处理
 */
@Component
@Slf4j
public class AuthChangeHandler extends AbstractHandler {

	private final WxCorpService wxCorpService;
	private final WxAdminService wxAdminService;
	private final WxDepartmentService wxDepartmentService;
	
	@Autowired
	@Qualifier("singleThreadExecutor")
	private ExecutorService singleThreadExecutor;

	public AuthChangeHandler(WxCorpService wxCorpService,WxAdminService wxAdminService,WxDepartmentService wxDepartmentService) {
		super();
		this.wxCorpService = wxCorpService;
		this.wxAdminService = wxAdminService;
		this.wxDepartmentService = wxDepartmentService;
	}

	@Override
	public WxCpXmlOutMessage handle(WxCpTpXmlMessage wxMessage,
			Map<String, Object> context,
			WxCpTpService wxCpTpService,
			WxSessionManager sessionManager) {
		try {
			String suiteId = wxMessage.getSuiteId();
			String authCorpId = wxMessage.getAuthCorpId();
			WxCorp wxCorp = wxCorpService.getOne(new LambdaQueryWrapper<WxCorp>().eq(WxCorp::getCorpId, authCorpId).eq(WxCorp::getSuiteId,suiteId));
			WxCpTpAuthInfo  wxCpTpAuthInfo  = wxCpTpService.getAuthInfo(authCorpId, wxCorp.getPermanentCode());
			
			wxCorp.setUpdatetime(LocalDateTime.now())
			.setVerifiedEndTime(new Date(wxCpTpAuthInfo.getAuthCorpInfo().getVerifiedEndTime()).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime())
			.setWxpackage(wxCpTpAuthInfo.toJson());
			
			wxCorpService.updateById(wxCorp);
			
			final WxCorp corp = wxCorp;
			
			// TODO: 后续应用初始化数据操作，审批模板复制...,异步线程执行
			singleThreadExecutor.execute(new Runnable() {
				
				@Override
				public void run() {
					//1. 同步应用管理员列表到本地数据库
					wxAdminService.syncAdminList(wxCpTpService, corp);
					
					//2. 同步企业部门及用户列表到本地数据库
					wxDepartmentService.syncDepartments(wxCpTpService, corp, true);
				}
			});
			
			log.info("更授权处理：" + wxCpTpAuthInfo);
		} catch (WxErrorException e) {
			log.error("更授权处理 err:" , e);
		}
		return null;
	}
}
